import React from 'react';
import { Modal, Form, Input, Select, message } from 'antd';
import { getArrayValue } from 'Utils/index';
import Api from 'Utils/api';
import './index.scss';

const Option = Select.Option;
const { TextArea } = Input;
const AddComandForm = Form.create()(
  (props) => {
    const { form } = props;
    const { getFieldDecorator } = form;

    return (
      <Form id="command-form">
        <FormItem >
          {getFieldDecorator('accepter', {
            rules: [
              { required: true, message: '请选择指令接受者' }
            ]
          })(
            <Select
              placeholder="请选择指令接受者"
              className="sel-input"
              mode="multiple"
              style={{ width: 280 }}
              getPopupContainer={() => document.getElementById('command-form')}
            >
              {
                props.renderExecutor()
              }
            </Select >
          )}
        </FormItem >
        <FormItem >
          {
            getFieldDecorator('content', {
              rules: [
                { required: true, message: '请输入' }
              ]
            })(
              <TextArea placeholder="新指令的内容，由指挥中心执行编辑" rows={4} style={{ width: 500 }} />
            )
          }
        </FormItem >
      </Form >
    );
  }
);
const FormItem = Form.Item;
class AddModal extends React.PureComponent {
  constructor(props) {
    super(props);
    this.state = {
      visible: false,
      taskId: '',
      peopleInfo: [],
      loading: false
    };
    this.renderExecutorParent = ::this.renderExecutorParent;
    this.getTaskDetail = ::this.getTaskDetail;
  }

  show(id) {
    this.setState({ visible: true, taskId: id }, () => {
      this.form.resetFields();
      this.getTaskDetail();
    });
  }

  close() {
    this.setState({
      visible: false,
      loading: false
    });
    this.props.handleModalClose();
  }

  getTaskDetail() {
    const api = new Api({
      method: 'GET',
      path: `/tasks/${this.state.taskId}`,
      success: (res) => {
        const nameArr = res.law_executor;
        const idArr = res.law_executor_ids;
        const peopleInfo = [];
        for (let i = 0, len = idArr.length; i < len; i++) {
          const item = {
            id: idArr[i],
            name: nameArr[i]
          };
          peopleInfo.push(item);
        }
        this.setState({
          peopleInfo
        });
      },
      eoor: (msg) => {
        message.error(msg);
      }
    });
    api.run();
  }
  onHandleOk() {
    const formValue = this.form.getFieldsValue();
    this.form.validateFieldsAndScroll((err) => {
      if (!err) {
        const self = this;
        this.setState({ loading: true });
        const api = new Api({
          method: 'POST',
          path: `/instructions/${this.state.taskId}`,
          data: {
            content: formValue.content,
            accepter: getArrayValue(self.state.peopleInfo, formValue.accepter),
            accepter_ids: formValue.accepter.map(item => parseInt(item, 10)),
          },
          success: () => {
            self.close();
            this.props.onEdit();
          },
          error: (msg) => {
            this.setState({ loading: false });
            message.error(msg);
          },
        });
        api.run();
      }
    });
  }

  onCancel() {
    this.close();
  }
  renderExecutorParent() {
    const children = [];
    const { peopleInfo } = this.state;
    console.log(peopleInfo);
    for (let i = 0; i < peopleInfo.length; i++) {
      children.push(<Option key={peopleInfo[i].id} value={peopleInfo[i].id.toString()} >{peopleInfo[i].name}</Option>);
    }
    return children;
  }
  render() {
    return (
      <Modal
        title="新建指令"
        wrapClassName="vertical-center-modal"
        visible={this.state.visible}
        className="add-modal command small-modal"
        onOk={this.onHandleOk.bind(this)}
        onCancel={this.onCancel.bind(this)}
        width={798}
        confirmLoading={this.state.loading}
      >
        <div >
          <AddComandForm
            ref={(ref) => { this.form = ref; }}
            renderExecutor={this.renderExecutorParent}
          />
        </div >
      </Modal >
    );
  }
}

export default AddModal;

